# coding=utf-8
"""
Subtitle Decoder
Uses some library files from
http://xbmc-addon-repository.googlecode.com
Thanks!
"""
import sys
import os
import pdb
from os import path, access, W_OK
from urlparse import urlparse
from BeautifulSoup import BeautifulSoup
from crunchyDec import crunchyDec
from crunchy_video import CrunchyPlayback

xmlSource = sys.argv[1]
#offline xml decoding
if xmlSource.lower().endswith(".xml"):
	xmlSource = open(sys.argv[1])
	formattedSubs = crunchyDec().returnSubs(xmlSource)
	try:
		subfile = open(sys.argv[2], 'w')
	except IndexError:
		subfile = open('video.ass', 'w')
	subfile.write(formattedSubs.encode('utf-8-sig'))
	subfile.close()

#url decoding
else:
	url = sys.argv[1]
	url_parse = urlparse(url)
	renamed = "0"
	CP = CrunchyPlayback()
	html = CP.downloadHTML(url)
	soup = BeautifulSoup(html)
	title = soup.title.string
	title = title.encode('utf-8') #grrrr...
	title = title.replace('Crunchyroll - Watch ','').replace('/',' - ').replace(':',' -').replace('?','.').replace('&quot;','\'').replace('’','\'').replace('–','-') #clean title
	#change the language in the quotes "" for other languages. DO NOT remove the u" or it f's everything up
	subtitle = soup.find(title=u"English (US)")
	try:
		subtitle = "http://www.crunchyroll.com" + subtitle.get('href')
	except AttributeError: #no subtitles
		file = open(title + '.ass', 'wb')
		file.write('[Script Info]\r\nVideo Zoom Percent: 1\r\nScriptType: v4.00+\r\n[V4+ Styles]\r\nFormat: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\r\nStyle: Default,Arial,20,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,2,2,2,10,10,10,1\r\n[Events]\r\nFormat: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\r\nDialogue: 0,0:00:00.00,0:00:05.00,Default,,0,0,0,,')
		file.close()
		sys.exit(title + ' has hardcoded subtitles.')
	subtitle = urlparse(subtitle)
	subtitle = subtitle[4].split('ssid=')
	subtitle = subtitle[1]
	suburl = "http://www.crunchyroll.com/xml/?req=RpcApiSubtitle_GetXml&subtitle_script_id=" + subtitle
	assfile = title + ".ass"
	print "CRUNCHYROLL: --> Determined Subtitle URL: "+suburl
	print "CRUNCHYROLL: --> Generated filename."
	xmlSource = CP.downloadHTML(suburl)
	formattedSubs = crunchyDec().returnSubs(xmlSource)
	while path.exists(assfile) and path.isfile(assfile): #file already exists
		print "CRUNCHYROLL: --> Destination file already exists!"
		renamed = "1"
		assfile = raw_input("CRUNCHYROLL: --> Filename? (Leave extension off): ")+".ass"
	if renamed == "1":
		print "CRUNCHYROLL: --> Using filename: "+assfile
	os.path.isfile(assfile)
	subfile = open(assfile, 'wb')
	subfile.write(formattedSubs.encode('utf-8-sig'))
	subfile.close()